package com.xz.knowledgeDuplication.juc.jmm;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 不保证原子性
 *
 * @author 召
 * @date 2022-11-08 21:56:11
 */
public class VolatileTest02 {

    private volatile static AtomicInteger num = new AtomicInteger();

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
               for (int j = 0; j < 1000; j++) {
                   add();
               }
            }).start();
        }
        while (Thread.activeCount() > 2) { // main gc
            Thread.yield();
        }
        System.out.println("num: " + num);
    }

    public static void add() {
        // num++; // 不是一个原子性操作
        num.getAndIncrement(); // AtomicInteger + 1 方法, CAS
    }
}
